const db = wx.cloud.database()
Page({
  data: {
    formats: {},
    readOnly: false,
    placeholder: '输入内容...',
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false,
    title: '',
    nodes: '',
    id: ''
  },

  //获取note集合中的记录，并渲染
  getNote: function () {
    wx.showLoading({
      title: '加载中',
    })
    db.collection('note').doc(this.data.id).get().then(res => {
      this.setData({
        title: res.data.title
      })
      this.editorCtx.setContents({
        html: res.data.content,
        success: function (res) {
          wx.hideLoading()
        }
      })
    })
  },
  bindKeyInput: function (e) {
    this.setData({
      title: e.detail.value
    })
  },

  //如果有id是修改数据，否则是添加数据
  tijiao: function () {
    const that = this;
    this.editorCtx.getContents({
      success: function (res) {
        if (that.data.id) {
          that.editnote(res.html,res.text)
        } else {
          that.addnote(res.html,res.text)
        }

      }
    })
  },

  //修改数据
  editnote: function (content,text) {
    db.collection('note').doc(this.data.id).update({
      data: {
        title: this.data.title,
        content: content,
        text:text,
        type:1,
        create_time: new Date()
      }
    }).then(res => {
      wx.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000
      })
      setTimeout(function () {
        wx.switchTab({
          url: '../index/index'
        })
      }, 2000)
    }).catch(console.error)
  },

  //添加数据
  addnote: function (content,text) {
    db.collection('note').add({
      data: {
        title: this.data.title,
        content: content,
        text:text,
        type:1,
        create_time: new Date()
      }
    }).then(res => {
      this.setData({
        id: res._id
      })
      wx.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000
      })
      setTimeout(function () {
        wx.switchTab({
          url: '../index/index'
        })
      }, 3000)
    }).catch(console.error)
  },
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },

  onLoad: function (e) {
    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({ isIOS })
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })
    if (e.id) {
      this.setData({
        id: e.id
      })
    }
  },

  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const { windowHeight, platform } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({ editorHeight, keyboardHeight })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const { statusBarHeight, platform } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec()
    if (this.data.id) {
      this.getNote()
    }

  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let { name, value } = e.target.dataset
    if (!name) return
    this.editorCtx.format(name, value)

  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({ formats })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {

      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },


  // 上传图片
  uploadPhoto(filePath) {
    wx.showLoading({
      title: '加载中',
    })
    // 调用wx.cloud.uploadFile上传文件
    return wx.cloud.uploadFile({
      cloudPath: 'node/' + `${Date.now()}-${Math.floor(Math.random(0, 1) * 10000000)}`+filePath.match(/\.[^.]+?$/)[0],
      filePath
    })
  },
  insertImage() {
    const that = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        that.uploadPhoto(res.tempFilePaths[0]).then(res => {
         
          that.editorCtx.insertImage({
            src: res.fileID,
            data: {
              id: 'abcd',
              role: 'god'
            },
            width: '100%',
            success: function () {
              wx.hideLoading()
              console.log('insert image success')
            }
          })
        })

      }
    })
  }
})
